﻿using System;
using Consul;
using Microsoft.Extensions.Configuration;

namespace General.Mvc.Middleware
{
    public static class ConsulHelper
    {
        public static void ConsulRegist(this IConfiguration Configuration)
        {
            ConsulClient client = new ConsulClient(c =>
            {
                c.Address = new Uri(Configuration["ConsulUrl"]);
                c.Datacenter = "dc1";

            });
            string ip = string.IsNullOrEmpty(Configuration["ip"])?"127.0.0.1": Configuration["ip"];
            int port = Convert.ToInt32(Configuration["port"])==0?555: Convert.ToInt32(Configuration["port"]);
            int weight = Convert.ToInt32(Configuration["weight"]) == 0 ? 1 : Convert.ToInt32(Configuration["weight"]);
            client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID="service-"+Guid.NewGuid(),
                 Name="GeneralNetCore",
                 Address= Configuration["ServerIp"],//本服务公网ip
                 Port= port,
                 //Tags = null,
                 Tags = new string[] { weight.ToString() },
                 Check=new AgentServiceCheck()
                 {
                      Interval = TimeSpan.FromSeconds(10),
                      HTTP=$"http://{ip}:{port}/Home/HealthCheck",
                      Timeout=TimeSpan.FromSeconds(5), //检测等待时间
                      DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(60) //失败多久过后移除
                 }
            });
        }

    }
}
